
package org.kernely.stream.messageFilter;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.kernely.mail.service.KernelyMailPreparation;
import org.kernely.security.dao.UserDAO;
import org.kernely.security.dao.UserDetailsDAO;
import org.kernely.security.persistence.User;
import org.kernely.stream.StreamBundle;
import org.kernely.stream.service.StreamFilter;

/**
 *	Filter messages with regex to detect "@login" pattern and send a mail.
 */
public class MailFilter implements StreamFilter{

	/**
	 * @see org.kernely.stream.service.StreamFilter#applyFilter(java.lang.String)
	 */
	public String applyFilter(String messageToFilter) {
		
		String txt = messageToFilter;
		String regexp = "@(\\S)*";

		Pattern pattern = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(txt);
		StringBuffer buffer = new StringBuffer();
		while (matcher.find()) {
			String login = matcher.group(0);
			boolean loginExists = notifyUser(login.substring(1, login.length()), messageToFilter);
			
			// Modify the display of the login if it exists
			if (loginExists){
				matcher.appendReplacement(buffer, "<span style=\"color:purple;\">"+ login +"</span>");
			} else {
				matcher.appendReplacement(buffer, login);
			}
		}
		matcher.appendTail(buffer);
		return buffer.toString();
	}
	
	/**
	 * Try to notify the user by mail.
	 * @param login The login of the user.
	 * @message message The message where the user is mentioned.
	 * @return True if the user exists and has defined a mail, false otherwise.
	 */
	private boolean notifyUser(String login,String message){
		User user = UserDAO.getInstance().findUser(login);
		if (user == null){
			return false;
		}
		else {
		     // Create a KernelyMailPreparation, containing infos.
			KernelyMailPreparation mail = new KernelyMailPreparation("Your name appears in a message",
					"You were mentioned in a message:<br/><br/>-------<br/>"+message+"<br>-------");

			StreamBundle.getMailService().sendMail(mail, UserDetailsDAO.getInstance().getUserDetails(user).getMail());

			return true;
		}
	}
}

